package com.magicsoft.share.utils;

import android.content.Context;
import android.content.DialogInterface;
import android.util.Log;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.magicsoft.share.R;

import java.util.ArrayList;
import java.util.Date;

import cn.pedant.SweetAlert.SweetAlertDialog;

/**
 * Created by lyf on 2017/9/20/020.
 * 阿里云工具类
 */

public class OssManager {
    private OSS oss;
    private Context mContext;
    private String ACCESS_ID = "LTAIUg3wkXF7q4Bf ";
    private String ACCESS_KEY = "6jDimXrKDg73moXvDoFlZCbnv5jldt";
    private String OSS_ENDPOINT = "oss-cn-hangzhou.aliyuncs.com";


    private String BUCKET_NAME = "wind-qixiang";
    private String baseUrl = "http://wind-qixiang.oss-cn-hangzhou.aliyuncs.com/";

    private int position = 0;
    private String name = "QX";
    private ArrayList<String> urlList;
    private SweetAlertDialog dialog;
    private Date date;

    public static OssManager getInstance() {
        return OssInstance.instance;
    }

    private static class OssInstance {
        private static final OssManager instance = new OssManager();
    }

    private OssManager() {
    }

    private String bucketName;

    public OssManager init(Context context) {
        return init(context, OSS_ENDPOINT, BUCKET_NAME, ACCESS_ID, ACCESS_KEY);
    }

    /**
     * 初始化
     **/
    public OssManager init(Context context, String endpoint, String bucketName, String accessKeyId, String accessKeySecret) {
        if (oss == null) {
            mContext = context;

            urlList = new ArrayList<>();
            OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(accessKeyId, accessKeySecret);
            oss = new OSSClient(context, endpoint, credentialProvider);
            dialog = new SweetAlertDialog(mContext, SweetAlertDialog.PROGRESS_TYPE);
            dialog.getProgressHelper().setBarColor(R.color.main);
            dialog.setTitleText("加载图片中...");
            dialog.setCancelable(true);
            dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialogInterface) {
                    position = 0;
                }
            });
        }
        this.bucketName = bucketName;
        return OssInstance.instance;
    }

    public void refresh() {
        urlList.clear();
        dialog = new SweetAlertDialog(mContext, SweetAlertDialog.PROGRESS_TYPE);
        dialog.getProgressHelper().setBarColor(R.color.main);
        dialog.setTitleText("加载图片中...");
        dialog.setCancelable(true);
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialogInterface) {
                position = 0;
            }
        });
    }

    /**
     * 普通上传，比如image
     **/
    OSSAsyncTask task;

    public void upload(final ArrayList<String> filePath, final uploadListener listener) {
        dialog.show();


        Log.d("name", name + ":" + filePath);
        // 构造上传请求
        date = new Date();
        final long time = date.getTime();
        Log.d("url", "upload: " + filePath.get(position));
        PutObjectRequest put = new PutObjectRequest(bucketName, name + time + ".jpg", filePath.get(position));

        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                // Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
            }
        });
        task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.d("PutObject", "UploadSuccess");
                // 只有设置了servercallback，这个值才有数据
                // String serverCallbackReturnJson = result.getServerCallbackReturnBody();
                //Log.d("servercallback", serverCallbackReturnJson);
                String url = baseUrl + name + time + ".jpg";
                Log.d("url", "onSuccess: " + url);
                urlList.add(url);
                Log.d("lyf", "onSuccess: " + urlList.size() + filePath.size());
                if (urlList.size() == filePath.size()) {
                    position = 0;
                    dialog.dismiss();
                    listener.onSuccess(urlList);
                } else {

                    position++;
                    upload(filePath, listener);
                }

            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                position = 0;
                dialog.dismiss();
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
                listener.onFail();
            }
        });
    }


    public void upload(String filePath, final uploadListener2 listener) {
        Log.d("name", name + ":" + filePath);
        // 构造上传请求
        Date date = new Date();
        final long time = date.getTime();
        PutObjectRequest put = new PutObjectRequest(bucketName, name + time + ".jpg", filePath);

        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                // Log.d("PutObject", "currentSize: " + currentSize + " totalSize: " + totalSize);
            }
        });
        task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                Log.d("onSuccess", "UploadSuccess");
                // 只有设置了servercallback，这个值才有数据
                // String serverCallbackReturnJson = result.getServerCallbackReturnBody();
                //Log.d("servercallback", serverCallbackReturnJson);
                String url = baseUrl + name + time + ".jpg";
                listener.onSuccess(url);
                Log.d("onSuccess", "UploadSuccess" + url);
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                }
                if (serviceException != null) {
                    // 服务异常
                    Log.e("ErrorCode", serviceException.getErrorCode());
                    Log.e("RequestId", serviceException.getRequestId());
                    Log.e("HostId", serviceException.getHostId());
                    Log.e("RawMessage", serviceException.getRawMessage());
                }
                listener.onFail();
            }
        });
    }

    public interface uploadListener {
        void onSuccess(ArrayList<String> url);

        void onFail();
    }

    public interface uploadListener2 {
        void onSuccess(String url);

        void onFail();
    }
}
